package com.it.data.network.interceptor;

import com.it.common.utils.LogUtil;
import com.it.common.utils.NetworkUtils;
import com.it.data.manager.AppManager;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class NetworkInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        if (!NetworkUtils.INSTANCE.isNetworkAvailable(AppManager.appContext)) {
            LogUtil.d("NetworkInterceptor", "网络不可用=============");
            // 网络不可用时返回默认的响应
            String defaultMsg = "No network available";
            ResponseBody defaultBody = ResponseBody.create(MediaType.parse("text/plain"), defaultMsg);
            // 没有网络连接，直接返回一个空的 Response，表示拦截请求
            Protocol protocol = Protocol.HTTP_1_1; // 默认协议为 HTTP 1.1
            if (chain.connection() != null) {
                protocol = chain.connection().protocol() != null ? chain.connection().protocol() : Protocol.HTTP_1_1;
            }
            return new Response.Builder()
                    .code(504)
                    .request(chain.request())
                    .protocol(protocol)
                    .message("No network available") // 设置默认消息内容
                    .body(defaultBody)
                    .build();
        }
        LogUtil.d("NetworkInterceptor", "网络可用+++++++++++");
        // 有网络连接，继续进行请求
        Request request = chain.request();
        return chain.proceed(request);
    }
}